package cn.jhc.listener;

import java.sql.SQLException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.commons.dbutils.QueryRunner;
import org.h2.jdbcx.JdbcDataSource;

@WebListener
public class MyContextListener implements ServletContextListener {

	

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("context destoryed");

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		String path = sce.getServletContext().getRealPath("/h2demo");
		System.out.println(path);
		JdbcDataSource ds = new JdbcDataSource();
		ds.setURL("jdbc:h2:" + path);
		String sql = "create table if not exists user("
				+"id int auto_increment primary key,"
				+"username varchar(128) unique not null,"
				+"password varchar(128) not null,"
				+"filename varchar(128) not null,"
				+"sex char(1) not null,"
				+"intesters varchar(128))";
		String sql1 = "create table if not exists article("
				+ "id int auto_increment primary key,"
				+ "title varchar(128) not null,"
				+ "content text,"
				+ "userId int references user(id) "
				+ "publishDate datetime not null)";
		QueryRunner runner = new QueryRunner(ds);
		sce.getServletContext().setAttribute("Runner",runner );
		try {
		
		runner.execute(sql);
		runner.execute(sql1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
